import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';
import { verifyAuth, verifyDeletePermission } from '@/lib/auth-middleware';

// GET /api/device-parameters?deviceId=123&type=base_params
export async function GET(request: NextRequest) {
  try {
    // 验证用户认证状态
    const authResult = await verifyAuth();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }
    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');
    const type = searchParams.get('type'); // naming, position, base_params, tech_spec

    if (!deviceId) {
      return NextResponse.json({
        success: false,
        error: '缺少设备ID参数'
      }, { status: 400 });
    }

    const db = getDeviceParameterDb();
    const deviceData = db.getDeviceWithParameters(parseInt(deviceId));

    if (!deviceData) {
      return NextResponse.json({
        success: false,
        error: '设备不存在'
      }, { status: 404 });
    }

    if (type) {
      let tableName: string = '';
      let parameterData: any = {};
      
      // 检查 type 是表名还是参数类型
      if (type.startsWith('table_')) {
        // 直接使用表名
        tableName = type;
        // 根据表名推导参数类型
        const mapping = deviceData.mapping;
        if (mapping) {
          if (mapping.naming_table === type) {
            parameterData = deviceData.parameters.naming || {};
          } else if (mapping.position_table === type) {
            parameterData = deviceData.parameters.position || {};
          } else if (mapping.base_params_table === type) {
            parameterData = deviceData.parameters.base_params || {};
          } else if (mapping.tech_spec_table === type) {
            parameterData = deviceData.parameters.tech_spec || {};
          }
        }
      } else {
        // 使用参数类型
        parameterData = deviceData.parameters[type as keyof typeof deviceData.parameters];
        tableName = deviceData.mapping ?
          deviceData.mapping[`${type}_table` as keyof typeof deviceData.mapping] as string :
          '';
      }

      const fieldMetadata = tableName ? db.getParameterTableFields(tableName) : [];
      const tableMetadata = tableName ? db.getTableMetadata(tableName) : null;

      return NextResponse.json({
        success: true,
        data: {
          device: deviceData.device,
          mapping: deviceData.mapping,
          parameters: parameterData || {},
          fields: fieldMetadata,
          tableMetadata: tableMetadata
        }
      });
    } else {
      // 返回所有参数
      return NextResponse.json({
        success: true,
        data: deviceData
      });
    }

  } catch (error) {
    console.error('获取设备参数失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取设备参数失败'
    }, { status: 500 });
  }
}

// POST /api/device-parameters
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { deviceId, type, data } = body;

    if (!deviceId || !type || !data) {
      return NextResponse.json({
        success: false,
        error: '缺少必要参数'
      }, { status: 400 });
    }

    const db = getDeviceParameterDb();

    // 获取设备信息和映射
    const deviceData = db.getDeviceWithParameters(deviceId);
    if (!deviceData || !deviceData.mapping) {
      return NextResponse.json({
        success: false,
        error: '设备不存在或没有参数映射'
      }, { status: 404 });
    }

    const mapping = deviceData.mapping;
    const device = deviceData.device;

    // 根据类型确定表名
    let tableName: string;
    let recordIdField: string;

    switch (type) {
      case 'naming':
        tableName = mapping.naming_table;
        recordIdField = 'naming_record_id';
        break;
      case 'position':
        tableName = mapping.position_table;
        recordIdField = 'position_record_id';
        break;
      case 'base_params':
        tableName = mapping.base_params_table;
        recordIdField = 'base_params_record_id';
        break;
      case 'tech_spec':
        tableName = mapping.tech_spec_table || '';
        recordIdField = 'tech_spec_record_id';
        break;
      default:
        return NextResponse.json({
          success: false,
          error: '无效的参数类型'
        }, { status: 400 });
    }

    if (!tableName) {
      return NextResponse.json({
        success: false,
        error: '该设备类型不支持此参数类型'
      }, { status: 400 });
    }

    let recordId: number;

    // 检查是否已有记录
    const existingRecordId = device[recordIdField];

    if (existingRecordId) {
      // 更新现有记录
      db.updateParameterRecord(tableName, existingRecordId, data);
      recordId = existingRecordId;
    } else {
      // 创建新记录
      recordId = db.createParameterRecord(deviceId, tableName, data);

      // 更新设备的记录引用
      db.updateDeviceParameterReferences(deviceId, {
        [recordIdField]: recordId
      });
    }

    // 返回更新后的数据
    const updatedRecord = db.getParameterRecord(tableName, recordId);

    return NextResponse.json({
      success: true,
      data: {
        recordId,
        parameters: updatedRecord
      }
    });

  } catch (error) {
    console.error('保存设备参数失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '保存设备参数失败'
    }, { status: 500 });
  }
}

// DELETE /api/device-parameters?deviceId=123&type=base_params
export async function DELETE(request: NextRequest) {
  try {
    // Verify authentication and delete permissions
    const authResult = await verifyDeletePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canDelete) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法删除设备参数'
      }, { status: 403 });
    }

    const { searchParams } = new URL(request.url);
    const deviceId = searchParams.get('deviceId');
    const type = searchParams.get('type');

    if (!deviceId || !type) {
      return NextResponse.json({
        success: false,
        error: '缺少必要参数'
      }, { status: 400 });
    }

    const db = getDeviceParameterDb();

    // 获取设备信息和映射
    const deviceData = db.getDeviceWithParameters(parseInt(deviceId));
    if (!deviceData || !deviceData.mapping) {
      return NextResponse.json({
        success: false,
        error: '设备不存在或没有参数映射'
      }, { status: 404 });
    }

    const mapping = deviceData.mapping;
    const device = deviceData.device;

    // 根据类型确定表名和记录ID字段
    let tableName: string;
    let recordIdField: string;

    switch (type) {
      case 'naming':
        tableName = mapping.naming_table;
        recordIdField = 'naming_record_id';
        break;
      case 'position':
        tableName = mapping.position_table;
        recordIdField = 'position_record_id';
        break;
      case 'base_params':
        tableName = mapping.base_params_table;
        recordIdField = 'base_params_record_id';
        break;
      case 'tech_spec':
        tableName = mapping.tech_spec_table || '';
        recordIdField = 'tech_spec_record_id';
        break;
      default:
        return NextResponse.json({
          success: false,
          error: '无效的参数类型'
        }, { status: 400 });
    }

    const recordId = device[recordIdField];

    if (recordId) {
      // 删除参数记录
      db.deleteParameterRecord(tableName, recordId);

      // 清除设备的记录引用
      db.updateDeviceParameterReferences(parseInt(deviceId), {
        [recordIdField]: null
      });
    }

    return NextResponse.json({
      success: true,
      message: '参数记录已删除'
    });

  } catch (error) {
    console.error('删除设备参数失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '删除设备参数失败'
    }, { status: 500 });
  }
}